$(function () {
	// 获取用户数据
	var id = sessionStorage.getItem("id");
	var token = sessionStorage.getItem("token");

	axios
		.get(`http://localhost:9000/users/info?id=${id}`, {
			headers: {
				authorization: token,
			},
		})
		.then(res => {
			if (res.data.code === 1) {
				$(".username").val(res.data.user.username);
				$(".age").val(res.data.user.age);
				$(".gender").val(res.data.user.gender);
				$(".nickname").val(res.data.user.nickname);
			}
		});
	// 表单验证
	$("form").on("submit", function (event) {
		event.preventDefault(); // 阻止表单默认提交

		var username = $('input[name="username"]').val();
		var age = $('input[name="age"]').val();
		var gender = $('select[name="gender"]').val();
		var nickname = $('input[name="nickname"]').val();

		// 简单的前端验证
		if (!username || !age || !gender || !nickname) {
			alert("请填写所有必填项");
			return;
		}

		axios
			.post(
				"http://localhost:9000/users/update",
				{
					id: id,
					age: age,
					gender: gender,
					nickname: nickname,
				},
				{
					headers: {
						authorization: token,
					},
				}
			)
			.then(function (response) {
				if (response.data.code === 1) {
					alert(response.data.message);
					sessionStorage.setItem("nickname", nickname);
				} else {
					alert(response.data.message);
				}
			});
	});
});
